package service

import (
	"context"
	"flare-admin/db/sqlc/ddos"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
)

// DDoSFlowSyncService DDoS流量数据同步服务
type DDoSFlowSyncService struct {
	service    *Service
	ctx        context.Context
	cancel     context.CancelFunc
	wg         sync.WaitGroup
	updateChan chan []ddos.OteldemoDdosFlow
	ticker     *time.Ticker
	mu         sync.RWMutex
	lastUpdate time.Time
}

// NewDDoSFlowSyncService 创建DDoS流量数据同步服务
func NewDDoSFlowSyncService(service *Service) *DDoSFlowSyncService {
	ctx, cancel := context.WithCancel(context.Background())
	
	return &DDoSFlowSyncService{
		service:    service,
		ctx:        ctx,
		cancel:     cancel,
		updateChan: make(chan []ddos.OteldemoDdosFlow, 100), // 缓冲100个更新
		ticker:     time.NewTicker(30 * time.Second), // 每30秒检查一次
	}
}

// Start 启动数据同步服务
func (s *DDoSFlowSyncService) Start() {
	logrus.Debug("[DDoSFlowSyncService] - starting ddos flow sync service")
	
	s.wg.Add(2)
	
	// 启动定时检查任务
	go s.periodicSync()
	
	// 启动数据更新处理任务
	go s.processUpdates()
	
	logrus.Debug("[DDoSFlowSyncService] - ddos flow sync service started")
}

// Stop 停止数据同步服务
func (s *DDoSFlowSyncService) Stop() {
	logrus.Debug("[DDoSFlowSyncService] - stopping ddos flow sync service")
	
	s.cancel()
	s.ticker.Stop()
	
	// 等待所有goroutine结束
	s.wg.Wait()
	
	logrus.Debug("[DDoSFlowSyncService] - ddos flow sync service stopped")
}

// UpdateFlows 更新流量数据
func (s *DDoSFlowSyncService) UpdateFlows(flows []ddos.OteldemoDdosFlow) {
	select {
	case s.updateChan <- flows:
		logrus.Debugf("[DDoSFlowSyncService] - queued %d flows for update", len(flows))
	default:
		logrus.Warn("[DDoSFlowSyncService] - update channel is full, dropping update")
	}
}

// periodicSync 定时同步任务
func (s *DDoSFlowSyncService) periodicSync() {
	defer s.wg.Done()
	
	for {
		select {
		case <-s.ctx.Done():
			return
		case <-s.ticker.C:
			s.checkForUpdates()
		}
	}
}

// processUpdates 处理数据更新
func (s *DDoSFlowSyncService) processUpdates() {
	defer s.wg.Done()
	
	for {
		select {
		case <-s.ctx.Done():
			return
		case flows := <-s.updateChan:
			s.handleFlowUpdate(flows)
		}
	}
}

// checkForUpdates 检查是否有新数据需要更新
func (s *DDoSFlowSyncService) checkForUpdates() {
	s.mu.RLock()
	lastUpdate := s.lastUpdate
	s.mu.RUnlock()
	
	// 获取最新的流量数据
	dbFlows, err := s.service.GetAllDDoSFlowsFromDB(s.ctx)
	if err != nil {
		logrus.Errorf("[DDoSFlowSyncService] - failed to get ddos flows: %v", err)
		return
	}
	
	// 检查是否有新数据
	if len(dbFlows) > 0 && (s.lastUpdate.IsZero() || dbFlows[0].CreatedAt.After(lastUpdate)) {
		logrus.Debugf("[DDoSFlowSyncService] - detected new ddos flows, updating cache")
		
		s.mu.Lock()
		s.lastUpdate = time.Now()
		s.mu.Unlock()
		
		// 通知前端或其他服务有新数据
		s.notifyNewData(dbFlows)
	}
}

// handleFlowUpdate 处理流量数据更新
func (s *DDoSFlowSyncService) handleFlowUpdate(flows []ddos.OteldemoDdosFlow) {
	logrus.Debugf("[DDoSFlowSyncService] - processing update for %d flows", len(flows))
	
	// 这里可以添加具体的更新逻辑，比如：
	// 1. 更新内存缓存
	// 2. 发送WebSocket通知给前端
	// 3. 触发数据分析
	// 4. 发送告警等
	
	s.mu.Lock()
	s.lastUpdate = time.Now()
	s.mu.Unlock()
	
	logrus.Debugf("[DDoSFlowSyncService] - successfully processed update for %d flows", len(flows))
}

// notifyNewData 通知有新数据
func (s *DDoSFlowSyncService) notifyNewData(flows []ddos.OteldemoDdosFlow) {
	// 这里可以实现具体的通知逻辑
	// 比如通过WebSocket推送给前端，或者触发其他服务
	
	logrus.Debugf("[DDoSFlowSyncService] - notifying about %d new flows", len(flows))
	
	// 示例：记录最新的流量统计
	if len(flows) > 0 {
		attackFlows := 0
		normalFlows := 0
		
		for _, flow := range flows {
			if flow.FlowType != "正常流量" {
				attackFlows++
			} else {
				normalFlows++
			}
		}
		
		logrus.Debugf("[DDoSFlowSyncService] - flow statistics: normal=%d, attack=%d", normalFlows, attackFlows)
	}
}

// GetLastUpdateTime 获取最后更新时间
func (s *DDoSFlowSyncService) GetLastUpdateTime() time.Time {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.lastUpdate
}

// GetStats 获取同步服务统计信息
func (s *DDoSFlowSyncService) GetStats() map[string]interface{} {
	s.mu.RLock()
	defer s.mu.RUnlock()
	
	return map[string]interface{}{
		"last_update": s.lastUpdate,
		"is_running":  s.ctx.Err() == nil,
		"queue_size":  len(s.updateChan),
	}
}

// 全局同步服务实例
var (
	ddosSyncService *DDoSFlowSyncService
	syncOnce        sync.Once
)

// InitDDoSFlowSyncService 初始化DDoS流量同步服务
func InitDDoSFlowSyncService(service *Service) {
	syncOnce.Do(func() {
		ddosSyncService = NewDDoSFlowSyncService(service)
		ddosSyncService.Start()
		logrus.Debug("[InitDDoSFlowSyncService] - ddos flow sync service initialized")
	})
}

// GetDDoSFlowSyncService 获取DDoS流量同步服务实例
func GetDDoSFlowSyncService() *DDoSFlowSyncService {
	return ddosSyncService
}

// ShutdownDDoSFlowSyncService 关闭DDoS流量同步服务
func ShutdownDDoSFlowSyncService() {
	if ddosSyncService != nil {
		ddosSyncService.Stop()
		logrus.Info("[ShutdownDDoSFlowSyncService] - ddos flow sync service shutdown")
	}
}

